﻿using EnglishRemix.Services.Model;
using EnglishRemix.Services.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using EnglishRemix.Services.Model.Responses;

namespace EnglishRemix.Services.Facade
{
    public class ContentFacade
    {
        public ChapterResponse GetChapterByNumber(int chapterNumber)
        {
            ChapterResponse chapterResponse = new ChapterResponse();

            String sqlString = @"SELECT 
                                    c.Number AS ChapterNumber,
                                    c.Description AS ChapterDesc,
                                    c.Content AS ChapterContent
                                FROM Chapter c WHERE c.Number = @chapterNumber";

            List<SqlParameter> sqlParam = new List<SqlParameter>();
            DBUtility.AddSqlParam(sqlParam, "@chapterNumber", System.Data.SqlDbType.BigInt, chapterNumber);
            DataSet ds = DBUtility.ExecuteDataset(sqlString, sqlParam);

            if(ds!=null && ds.Tables!=null && ds.Tables.Count>0 && ds.Tables[0].Rows != null && ds.Tables[0].Rows.Count>0)
            {
                chapterResponse.number = chapterNumber;
                chapterResponse.description = ds.Tables[0].Rows[0]["ChapterDesc"].ToString();
                chapterResponse.content = ds.Tables[0].Rows[0]["ChapterContent"].ToString();
            }
            return chapterResponse;
        }

        public ChapterListResponse GetChapterList()
        {
            ChapterListResponse chapterListResponse = new ChapterListResponse();

            String sqlString = "SELECT c.Number AS ChapterNumber from Chapter c LEFT JOIN PageInfo p on 1=1 WHERE 1=1 GROUP BY c.Number;";
            List<SqlParameter> sqlParam = new List<SqlParameter>();
            DataSet ds = DBUtility.ExecuteDataset(sqlString, sqlParam);
            if (DBUtility.hasResult(ds))
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    int chapterNumber = Convert.ToInt32(dr["ChapterNumber"]);
                    ChapterResponse chapterResponse = GetChapterByNumber(chapterNumber);
                    ChapterInfo chapterInfo = new ChapterInfo();
                    chapterInfo.ChapterNumber = chapterResponse.number;
                    chapterInfo.ChapterDesc = chapterResponse.description;
                    chapterListResponse.ChapterList.Add(chapterInfo);
                }
            }
            return chapterListResponse;
        }

    }
}